<template>
    <main-page layout="hm">
        <template #header>
            <el-breadcrumb separator-class="icon-arrow-right">
                <el-breadcrumb-item v-for="(item, index) in breadcrumb.data.items" :key="item">
                    <el-link v-if="index !== breadcrumb.data.items.length -1 " :underline="false" style="text-decoration: none" type="primary"
                             @click="breadcrumb.handle.toBreadcrumbItem(item, index)"> {{ item[breadcrumb.props.label] }}
                    </el-link>
                    <el-link v-else :underline="false" style="text-decoration: none" type="primary">{{ item[breadcrumb.props.label] }}</el-link>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </template>
        <data-table ref="dataTableRef"
                    :api="`/hadoop/list/${properties.data.uid}`"
                    :params="properties.params"
                    :primary-key="'path'"
                    :context-menu-extra="contextmenu.menus"
                    :before-open-context-menu="contextmenu.show"
                    :pagination="false"
                    selection select-on-row-click
                    @row-dbclick="properties.handle.open">
            <template #button>
                <el-button icon="el-icon-folder-add" @click="properties.handle.create()">新建文件夹</el-button>
                <el-button icon="el-icon-upload-filled" @click="properties.handle.upload()">上传</el-button>
            </template>
            <el-table-column align="left" width="45">
                <template #default="scope">
                    <el-image :src="fileIcon(scope.row.extension)" style="position: relative;float: left; width: 1.8em;height: 1.8em;"/>
                </template>
            </el-table-column>
            <el-table-column align="left" label="名称" prop="name" sortable>
                <template #default="scope">
                    <el-link :underline="false" style="text-decoration: none">{{ scope.row.name }}</el-link>
                </template>
            </el-table-column>
            <el-table-column align="left" label="修改日期" prop="modifyTime" sortable width="200"/>
            <el-table-column align="left" label="权限" prop="permissions" width="100"/>
            <el-table-column align="left" label="所有者" prop="owner" width="150"/>
            <el-table-column align="left" label="类型" prop="extension" width="180">
                <template #default="scope">
                    {{ scope.row.extension === 'folder' ? '文件夹' : scope.row.extension !== null && scope.row.extension !== '' ? scope.row.extension : '文件' }}
                </template>
            </el-table-column>
            <el-table-column align="right" header-align="center" label="大小" prop="length" width="150">
                <template #default="scope">
                    {{ sizeFormat(scope.row.length) }}
                </template>
            </el-table-column>
        </data-table>

        <paste-dialog ref="pasteDialogRef" :refresh="properties.handle.refresh"/>

        <uploader ref="uploaderRef"/>
    </main-page>
</template>

<script>
import {defineComponent, getCurrentInstance, onBeforeMount, onMounted, reactive, ref} from "vue";
import PasteDialog from './paste.vue'
import DataTable from '@/components/data-table/index.vue'
import {fileIcon, mitt, service, sizeFormat} from '@/utils';
import Uploader from "./upload.vue";

export default defineComponent({
    name: "hadoop",
    components: {DataTable, Uploader, PasteDialog},
    setup() {
        const {proxy} = getCurrentInstance();
        const dataTableRef = ref();
        const pasteDialogRef = ref();
        const uploaderRef = ref();

        const properties = reactive({
            params: {
                path: '/'
            },
            data: {
                uid: null,
                breadcrumbProps: {
                    label: 'name',
                    value: 'path'
                },
            },
            handle: {
                refresh: () => {
                    dataTableRef.value.refresh();
                },
                open: (row) => {
                    breadcrumb.handle.enter(row);
                },
                upload: () => {
                    uploaderRef.value.open({
                        target: properties.params.path,
                        uid: properties.data.uid
                    })
                },
                create: () => {
                    proxy.$messageBox.prompt('', {
                        title: '新建文件夹',
                        showClose: false,
                        inputValue: null,
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPlaceholder: '请输入文件夹名称',
                        draggable: true,
                        inputValidator: (v) => {
                            if (!v) {
                                return "文件夹名称不能为空"
                            }
                        },
                    }).then(({value}) => {
                        let path = properties.params.path === '/' ? properties.params.path + value : properties.params.path + '/' + value;
                        service.post(`/hadoop/mkdirs/${properties.data.uid}`, {path: path}).then(({code}) => {
                            if (code === 200) {
                                properties.handle.refresh();
                            }
                        })
                    }).catch(() => {
                    })
                },
                download: (rows) => {
                    const loadingInstance = proxy.$loading({text: `文件正在打包,请稍等...`})
                    const path = rows.map(item => item.path).join(',')
                    service.download(`/hadoop/download/${properties.data.uid}`, {path: path}, {timeout: 60000}).then(() => {
                        loadingInstance.close();
                    })
                },
                toLocal: (rows) => {
                    let dest = breadcrumb.data.items.last().path;
                    const path = rows.map(item => item.path).join(',')
                    service.post(`/hadoop/toLocal/${properties.data.uid}`, {dest: dest, path: path})
                },
                delete: (rows) => {
                    proxy.$confirm(`确定删除已选中文件:${rows.map(item => item.name).join(',')}?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const path = rows.map(item => item.path).join(',')
                        service.delete(`/hadoop/delete/${properties.data.uid}`, {path: path}).then(({code}) => {
                            if (code === 200) {
                                properties.handle.refresh();
                            }
                        })
                    });
                },
                paste: (operate, rows) => {
                    pasteDialogRef.value.show(rows, operate, properties.data.uid);
                }
            }
        })

        const breadcrumb = reactive({
            props: {
                label: 'name',
            },
            data: {
                items: []
            },
            handle: {
                init: (item) => {
                    breadcrumb.data.items.push(item);
                },
                // 面包屑-点击事件
                toBreadcrumbItem: (item, index = null) => {
                    if (index !== null) {
                        breadcrumb.data.items.splice(index + 1);
                    } else {
                        breadcrumb.data.items.push(item);
                    }
                    properties.params.path = item.path; // 根据数据表的唯一标识（主键）进行调整
                    properties.handle.refresh();
                },
                enter: (item) => {
                    breadcrumb.handle.toBreadcrumbItem(item)
                },
                backup: () => {
                    const length = breadcrumb.data.items.length;
                    if (length > 1) {
                        breadcrumb.handle.toBreadcrumbItem(breadcrumb.data.items[length - 2], length - 2);
                    }
                },
            }
        })

        const contextmenu = reactive({
            menus: [
                {
                    id: 'open',
                    label: "打开",
                    onClick: ({current}) => {
                        breadcrumb.handle.enter(current)
                    }
                },
                {
                    id: 'back',
                    label: "返回上一层",
                    icon: "icon-back",
                    onClick: () => breadcrumb.handle.backup(),
                },
                {
                    id: 'mkdir',
                    label: "新建文件夹",
                    icon: "el-icon-folder-add",
                    onClick: () => {
                        properties.handle.create();
                    }
                },
                {
                    id: 'fileTransfer',
                    label: "文件传输",
                    icon: 'el-icon-switch',
                    children: [
                        {
                            label: "上传文件",
                            icon: 'icon-cloud-upload',
                            onClick: () => properties.handle.upload()
                        },
                        {
                            label: "下载",
                            icon: 'icon-cloud-download',
                            onClick: ({selections}) => properties.handle.download(selections),
                        },
                        {
                            label: "拷贝至服务器",
                            icon: 'el-icon-copy-document',
                            onClick: ({selections}) => properties.handle.toLocal(selections),
                        },
                    ],
                },
                {separator: true},
                {
                    id: 'move',
                    label: "剪切",
                    icon: 'el-icon-scissor',
                    onClick: ({selections}) => properties.handle.paste('move', selections)
                },
                {
                    id: 'copy',
                    label: "复制",
                    icon: 'el-icon-document-copy',
                    onClick: ({selections}) => properties.handle.paste('copy', selections)
                },
                {separator: true},
                {
                    id: 'delete',
                    label: "删除",
                    icon: 'el-icon-delete',
                    onClick: ({selections}) => properties.handle.delete(selections)
                },
                {
                    id: 'rename',
                    label: "重命名",
                    icon: 'el-icon-edit',
                    onClick: ({current}) => {
                        proxy.$messageBox.prompt('', {
                            title: '重命名',
                            showClose: false,
                            inputValue: current.name,
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            inputPlaceholder: '请输入文件名称',
                            draggable: true,
                            inputValidator: (v) => {
                                if (!v) {
                                    return "文件名称不能为空"
                                }
                            },
                        }).then(({value}) => {
                            service.post(`/hadoop/rename/${properties.data.uid}`, {path: current.path, name: value}).then(({code}) => {
                                if (code === 200) {
                                    properties.handle.refresh();
                                }
                            })
                        }).catch(() => {
                        })
                    },
                },
            ],
            show: ({current, selections}, menus) => {
                menus.filter(it => it.hasOwnProperty("id")).forEach(item => {
                    switch (item.id) {
                        case 'open':
                            item.disabled = current?.extension !== 'folder';
                            break;
                        case 'copy':
                        case 'move':
                        case 'delete':
                            item.disabled = !selections.length
                            break;
                        case 'back':
                            item.disabled = breadcrumb.data.items.length <= 1
                            break;
                        case 'fileTransfer':
                            item.children[1].disabled = !selections.length
                            item.children[2].disabled = !selections.length
                            break
                        case 'rename':
                            item.disabled = !current
                            break;
                    }
                })
                return true;
            }
        })

        onBeforeMount(() => {
            let {query, meta} = proxy.$router.currentRoute.value;
            properties.data.uid = query.uid
            window.document.title = meta.title
        })

        onMounted(() => breadcrumb.handle.init({name: '根目录', path: '/'}))

        return {
            dataTableRef, pasteDialogRef, uploaderRef,
            properties, breadcrumb, contextmenu,
            fileIcon, sizeFormat,
        }
    }
})
</script>
